# Copyright (C) 2008 "Domenico Chierico" (spaghetty@gmail.com)
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.
import settings
import __init__

import types

def get_all_models():
    """Try to collect all active models defined into the apps"""
    from django.db import models
    apps = filter(__init__.clean_apps_list,settings.INSTALLED_APPS)
    results = {}
    for ap in apps:
        elem = __import__(ap+".models", globals(), locals(), ["*"])
        results[ap] = []
        for e in dir(elem):
            r = None
            try:
                r = __import__(ap+".models."+e,globals(), locals(),["*"])
            except:
                r = None
            if r!= None:
                for x in dir(r):
                    a = getattr(r,x)
                    try:
                        if issubclass(a, models.Model) and r.__name__.endswith(a.__module__):
                            results[ap].append(a)
                    except:
                        pass
    return results


def get_tagged_elem(tag):
    a = get_all_models()
    results=[]
    for apps in a:
        for model in a[apps]:
            if hasattr(model,tag) and isinstance(
                getattr(model,tag),type) or isinstance(
                getattr(model,tag),types.ObjectType):
                results.append(model)
    return results
